/**
 * Created by no1 on 2015/7/24.
 */
'use strict';

let mongoDao = require('./mongoDao/UserDao.js');
let roleDispatcher = require('./role.js');

function UserDispatcher() {
}
module.exports = new UserDispatcher();

let theProto = UserDispatcher.prototype;

/**
 * 增加角色,如果该角色已经存在,则会覆盖
 {
     "uid":123,
     "roleName": "管理员"
 }
 * @param inParams
 * @returns {*}
 */
theProto.add = function*(inParams) {
    let roleName = inParams.roleName;
    let exists = roleDispatcher.hasRole(roleName);
    if (exists.error) {
        return exists;
    }

    let result = yield mongoDao.saveOne(inParams);
    return result;
};

theProto.getByUserId = function*(uid) {
    let result = yield mongoDao.getById(uid);
    return result;
};

/**
 * 获取角色的权限图
 * @returns {null|*|result}
 */
theProto.permissions = function*(uid) {
    let user = yield this.getByUserId(uid);
    if (!user) {
        return {error: 'uid not exists'};
    }
    let roleName = user.roleName;
    let permission = yield roleDispatcher.permissions({roleName: roleName});
    return permission;
};

/**
 * 检测权限是否存在
 {
     "uid": 123,
     "permissions": [
         {"商家管理": ["添加商家","编辑商家"]},
         {"商家管理": ["添加商家","编辑商家"]}
     ]
 }
 */
theProto.checkMany = function*(inParams) {
    let user = yield this.getByUserId(inParams.uid);
    if (!user) {
        return {error: 'uid not exists'};
    }
    inParams.roleName = user.roleName;
    let result = yield roleDispatcher.checkMany(inParams);
    return result;
};